﻿using Furion.Localization;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using ST.Torch.WebApi.Application.System.Services;
using ST.Torch.WebApi.Application.System.Dtos;
using ST.Torch.WebApi.Core.Entities.System;
using System.Linq.Expressions;


namespace ST.Torch.WebApi.Application;

/// <summary>
/// 系统服务接口
/// </summary>

public class SystemAppService : IDynamicApiController
{
    private readonly ISystemService _systemService;
    private readonly ISYSUserService _SYSUserService;
 
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IUIDService _UIDService;


    public SystemAppService(ISystemService systemService, IHttpContextAccessor httpContextAccessor, ISYSUserService sYSUserService, IUIDService uIDService)
    {
        _systemService = systemService;
        _httpContextAccessor = httpContextAccessor;
        _SYSUserService = sYSUserService;
        _UIDService = uIDService;
    }

    /// <summary>
    /// 获取系统描述
    /// </summary>
    /// <returns></returns>
    public string GetDescription()
    {
        return _systemService.GetDescription();
    }

    /// <summary>
    /// 上传文件通用方法
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    [HttpPost, NonUnify]
    [RequestSizeLimit(100_000_000)]
    [AllowAnonymous]
    public async Task<dynamic> Uploadfiles(string filename)
    {

        try
        {

            if (_httpContextAccessor.HttpContext.Request.Form.Files.Count() == 0) return null;
            if (string.IsNullOrEmpty(filename))
            {
                filename = "Default";
            }
            string AutoFileName = _httpContextAccessor.HttpContext.Request.Form["AutofileName"];
            //文件的原始名称
            IFormFile UploadFile = _httpContextAccessor.HttpContext.Request.Form.Files[0];
            string FileOriginName = UploadFile.FileName;
            string fileSaveRootDir = "/uploads/file/" + filename;
            //string fileSaveRootDir = "/uploads/file/" + "Default";
            //生成文件的名称
            string Extension = Path.GetExtension(FileOriginName);//获取文件的源后缀
                                                                 //读取办公管理文件保存的模块的根目录
            string fileSaveDir = "";
            //文件保存的相对文件夹(保存到wwwroot目录下)
            string absoluteFileDir = fileSaveRootDir + "/" + fileSaveDir;
            //文件保存的路径(应用的工作目录+文件夹相对路径);
            string fileSavePath = Environment.CurrentDirectory + "/wwwroot/" + absoluteFileDir;
            //string fileSavePath = Environment.CurrentDirectory + "" + absoluteFileDir;
            if (!Directory.Exists(fileSavePath))
            {
                Directory.CreateDirectory(fileSavePath);
            }
            if (string.IsNullOrEmpty(Extension))
            {
                throw new Exception("文件上传的原始名称好像不对哦，没有找到文件后缀");
            }
            //string fileName = Guid.NewGuid().ToString() + Extension;//通过uuid和原始后缀生成新的文件名
            string fileName = AutoFileName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + Extension;//通过uuid和原始后缀生成新的文件名
            if (string.IsNullOrEmpty(AutoFileName))
            {
                fileName = Guid.NewGuid().ToString() + Extension;//通过uuid和原始后缀生成新的文件名
            }
            //最终生成的文件的相对路径（xxx/xxx/xx.xx）
            string finalyFilePath = fileSavePath + "/" + fileName;



            //打开上传文件的输入流
            Stream stream = UploadFile.OpenReadStream();


            //开始保存拷贝文件
            FileStream targetFileStream = new FileStream(finalyFilePath, FileMode.OpenOrCreate);
            await stream.CopyToAsync(targetFileStream);
            stream.Close();
            await stream.DisposeAsync();
            targetFileStream.Close();
            await targetFileStream.DisposeAsync();
            return new
            {
                code = 200,
                msg = "上传成功",
                data = absoluteFileDir + fileName

            };


        }
        catch (Exception e)
        {
            return new
            {
                code = 500,
                msg = e,
                data = ""
            };
        }
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<dynamic> Login([FromForm]string Account, [FromForm] string Password)
    {

        try
        {

            var userInfo = await _SYSUserService.SingleAsync(u => u.Account == Account);
            if (userInfo == null)
            {
                throw Oops.Oh($" {L.Text["账号不存在"]}");
            }
            else
            {
                if (userInfo.Password != userInfo.GetPassEncryption(Password))
                {
                    throw Oops.Oh($" {L.Text["密码错误"]}");
                }
                // 生成 token
                string accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
                {
                       { "UserId",userInfo.Id }
                    
                });
                /*
                //创建用户身份标识
                var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                claimsIdentity.AddClaims(new List<Claim>()
                    {
                        new Claim("UserId", userInfo.Id.ToString()),

                    });
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
                */
    
                return new { UserId = userInfo.Id, 
                    accessToken = accessToken  
                };
            }


        }
        catch (Exception e)
        {
            throw Oops.Oh($""+e.Message);
        }
    }

    /// <summary>
    /// 获取当前用户菜单
    /// </summary>
    /// <returns></returns>
    //[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]//jwt
    [AppAuthorize]
    [HttpGet,NonUnify]
    public List<LayuiMenuDto> GetCurrUserMenus()
    {

        try
        {
            if(L.GetCurrentUICulture().DisplayName!= "zh-CN")
            {
                var Menus = _UIDService.UserInfo.UIMenus.Adapt<List<LayuiMenuDto>>();
                setTitleLang(Menus);
                return Menus;
            }
            return _UIDService.UserInfo.UIMenus;
           
        }
        catch (Exception e)
        {
            throw Oops.Oh($"" + e.Message);
        }
    }
    /// <summary>
    /// 翻译目录名称
    /// </summary>
    /// <param name="Menus"></param>
    private void setTitleLang(List<LayuiMenuDto> Menus)
    {
        foreach (var item in Menus)
        {
            item.title = L.Text[item.title];
            if (item.children.Count() > 0)
            {
                setTitleLang(item.children);
            }
        }
              
    }
    [AppAuthorize]
    [HttpGet, NonUnify]
    public dynamic GetCurrUserInfo()
    {

        try
        {
            return new
            {
                User = _UIDService.User,
                PermissionIds = _UIDService.UserInfo.PermissionIds
            };

        }
        catch (Exception e)
        {
            throw Oops.Oh($"" + e.Message);
        }
    }



}
